import {
	defineStore
} from 'pinia'
import _ from 'lodash'

function isAlphabet(character) {
	// 使用正则表达式检查是否是英文字母
	return /^[a-zA-Z]/.test(character);

}
import {
	pinyin
} from 'pinyin-pro'
import {
	FormUserStoreKey
} from '../sotreKey';
export const useSelectUserPageStore = defineStore('useSelectUserPageStore', {
	state: () => ({
		userStoreKey: FormUserStoreKey,
		list: [],
		copyList: [],
		viewListData: [],

	}),
	actions: {
		clearUserStoreKeyValue(key, value) {
			this.userStoreKey[key].value = value || []
		},
		setUserStoreKeyValue(data, key) {
			this.userStoreKey[key].value = data
		},
		setInit(data) {
			this.list = data
			this.setViewListData(data)
		},
		setViewListData(data) {
			this.viewListData = data
		},
		delUserStoreKeyValue(index, key) {
			this.userStoreKey[key].value.splice(index, 1)
		},
		// clearUserStoreKeyValue(key) {
		// 	this.userStoreKey[key] = {
		// 		key,
		// 		label: null,
		// 		value: null
		// 	}
		// },
		onChangeKeywords: _.debounce(function(e) {
			const keyword = e.detail.value
			console.log(keyword === '');
			if (keyword) {
				const filters = _.filter(this.list, (item) => {
					return item.nickName.indexOf(keyword) > -1
				})
				this.setViewListData(filters)
			} else {
				this.setViewListData(this.list)
			}
		}, 400),
	},
	getters: {
		rewriteList() {
			let person = {}
			this.viewListData.forEach(item => {
				let first = null
				item['text'] = item.nickName
				item['value'] = String(item.userId)
				item['objectValue'] = JSON.stringify({
					name: item.nickName,
					value: item.userId
				})
				// 判断是否英文开头 
				if (isAlphabet(item.nickName)) {
					first = item.nickName.slice(0, 1)
					first = first.toUpperCase()
				} else {
					first = pinyin(item.nickName).slice(0, 1).toUpperCase()
				}
				if (person[first]) {
					person[first].push(item)
				} else {
					person[first] = [item]
				}
			})
			const list = []
			for (let i in person) {
				list.push({
					letter: i,
					data: person[i]
				})
			}
			list.sort((a, b) => {
				if (a.letter < b.letter) {
					return -1; // a 在 b 前面
				} else if (a.letter > b.letter) {
					return 1; // a 在 b 后面
				} else {
					return 0; // 顺序无变化
				}
			})
			return list
		},
		indexList() {
			return _.map(this.rewriteList, 'letter')
		}
	},
	persist: true,
})